package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

// 收货地址
@Service
@Transactional
public class AddressServiceImpl implements AddressService {


    @Autowired
    private AddressMapper addressMapper;


    // 地址列表
    @Override
    public List<Address> findList() {
        // 构建条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId()); // 用户id
        // 查询并返回
        List<Address> addressList = addressMapper.selectList(qw);
        return addressList;
    }


    // 新增地址
    @Override
    public void save(Address address) {
        // 补全信息
        address.setUserId(UserHolder.get().getId()); // 用户id
        address.setIsDefault(0); // 非默认地址

        // mapper新增
        addressMapper.insert(address);
    }

    //设置默认地址
    @Override
    public void setDefault(Map<String, Long> param) {
        //根据用户id查询Address表 找到对应地址信息
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());
        Address address = new Address();
        address.setIsDefault(0);
        addressMapper.update(address,qw);
        //取出id
        Long id = param.get("id");
       // LambdaQueryWrapper<AddressService> qw2 = new LambdaQueryWrapper<>();
        Address address1 = new Address();
        address1.setIsDefault(1);
        address1.setId(id);
        addressMapper.updateById(address1);

    }


    //查询(自动跳转)默认地址
    @Override
    public Address findDefault() {
        //根据用户id查询默认地址,默认地址为1
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());
        qw.eq(Address::getIsDefault,1);
        //返回查询结果
        return addressMapper.selectOne(qw);
    }


    //回显地址(修改前)
    @Override
    public Address findByAddressId(Long id) {
        //根据id查询
        Address address = addressMapper.selectById(id);
        return address;
    }


    //修改地址
    @Override
    public void updateByAddress(Address address) {
        //修改
        addressMapper.updateById(address);
    }


    //删除地址
    @Override
    public void deleteById(Long ids) {
        //根据前端传来的id删除地址
        addressMapper.deleteById(ids);
    }
}
